﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Net.Mime;
using Newtonsoft.Json.Linq;

namespace WpfApp1.Controller
{
    public class FileController
    {
        public static string ApiUrl { get; set; }
        public static string Token { get; set; }

        public static async void UploadFile(string selectedPath, string ext)
        {
            if (string.IsNullOrEmpty(selectedPath))
            {
                return;
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
                    client.DefaultRequestHeaders.Add("Authorization", Token);
                    //client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEzMDAwMDAwMDAxMTEsIlRlbmFudElkIjoxMzAwMDAwMDAwMDAxLCJBY2NvdW50IjoiYWRtaW4iLCJSZWFsTmFtZSI6Iuezu-e7n-euoeeQhuWRmCIsIkFjY291bnRUeXBlIjo4ODgsIk9yZ0lkIjoxMzAwMDAwMDAwMTAxLCJPcmdOYW1lIjoiQU1FQyIsIk9yZ1R5cGUiOiIxMDEiLCJpYXQiOjE3NDA3MjI4NzQsIm5iZiI6MTc0MDcyMjg3NCwiZXhwIjoxNzQxMzI3Njc0LCJpc3MiOiJBbWVjLkRpZ2l0aXphdGlvbiIsImF1ZCI6IkFtZWMuRGlnaXRpemF0aW9uIn0.yKImo6pUSfy0T1bcEtQMWGm_25ce2wal4YI-OVy4Qec");
                    using (MultipartFormDataContent formData = new MultipartFormDataContent())
                    {
                        // 检查文件是否存在
                        if (File.Exists(selectedPath))
                        {
                            // 打开文件流
                            using (FileStream fileStream = new FileStream(selectedPath, FileMode.Open, FileAccess.Read))
                            {
                                // 获取文件名
                                string fileName = Path.GetFileName(selectedPath);
                                // 将文件流内容读取到字节数组
                                byte[] fileBytes = new byte[fileStream.Length];
                                await fileStream.ReadAsync(fileBytes, 0, (int)fileStream.Length);

                                // 创建 ByteArrayContent 来封装文件字节数据
                                ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
                                // 设置 Content-Disposition 头信息，指定表单字段名和文件名
                                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                                {
                                    Name = "File",
                                    FileName = fileName
                                };
                                // 设置 Content-Type 头信息，指定文件的 MIME 类型
                                fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

                                // 将文件内容添加到表单数据中
                                formData.Add(fileContent);
                            }
                        }
                        else
                        {
                            Console.WriteLine($"文件 {selectedPath} 不存在。");
                            return;
                        }

                        // 发送 POST 请求到服务器
                        string url = ApiUrl + "/api/sysFile/uploadFile";
                        HttpResponseMessage response = await client.PostAsync(url, formData);

                        // 检查响应状态码
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"上传成功，服务器响应: {responseContent}");
                        }
                        else
                        {
                            Console.WriteLine($"上传失败，状态码: {response.StatusCode}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

        public static string GetFieldFromJsonByName(string filePath, string fieldName)
        {
            string value = "";
            try
            {
                string content = File.ReadAllText(filePath);
                // 解析 JSON 内容为 JObject
                JObject jsonObj = JObject.Parse(content);

                // 假设要查找的字段名为 "fieldName"，替换为实际的字段名
                JToken token = jsonObj[fieldName];
                if (token != null)
                {
                    // 根据字段值的类型进行处理
                    if (token.Type == JTokenType.String)
                    {
                        value = token.Value<string>();
                        Console.WriteLine($"找到字段 'fieldName' 的值: {value}");
                    }
                    else if (token.Type == JTokenType.Integer)
                    {
                        value = token.Value<int>().ToString();
                        Console.WriteLine($"找到字段 'fieldName' 的值: {value}");
                    }
                    // 可以根据需要添加更多类型的处理逻辑
                }

            } catch (Exception ex)
            {
                Console.WriteLine("Read Json File Exception:", $"{ex.Message}");
            }
            Token = value;
            return value;
        }
    }
}
